// src/composables/useTodos.js
import { ref, computed, watch, onMounted } from 'vue';

export default function useTodos() {
  // 数据定义
  const todos = ref([]);
  const newTodo = ref('');
  const filter = ref('all');
  const lastSavedTime = ref('');
  
  // 初始化函数
  const initialize = () => {
    // 从本地存储加载数据
    const savedTodos = localStorage.getItem('vue3-todos');
    if (savedTodos) {
      todos.value = JSON.parse(savedTodos);
      console.log('从本地存储加载了', todos.value.length, '个任务');
    }
    
    // 演示用：添加一些初始任务
    if (todos.value.length === 0) {
      todos.value = [
        { id: 1, text: '学习 Vue 3 基础', completed: true },
        { id: 2, text: '掌握组合式 API', completed: false },
        { id: 3, text: '完成 Todo List 项目', completed: false },
        { id: 4, text: '学习 Vuex 状态管理', completed: false },
        { id: 5, text: '学习 Vue Router', completed: false }
      ];
    }
    
    updateLastSavedTime();
  };
  
  onMounted(initialize);
  
  // 监听todos变化，保存到本地存储
  watch(todos, (newValue) => {
    localStorage.setItem('vue3-todos', JSON.stringify(newValue));
    updateLastSavedTime();
  }, { deep: true });
  
  // 计算属性
  const filteredTodos = computed(() => {
    switch (filter.value) {
      case 'active':
        return todos.value.filter(todo => !todo.completed);
      case 'completed':
        return todos.value.filter(todo => todo.completed);
      default:
        return todos.value;
    }
  });
  
  const remainingCount = computed(() => {
    return todos.value.filter(todo => !todo.completed).length;
  });
  
  const completedCount = computed(() => {
    return todos.value.filter(todo => todo.completed).length;
  });
  
  const completionRate = computed(() => {
    if (todos.value.length === 0) return 0;
    return Math.round((completedCount.value / todos.value.length) * 100);
  });
  
  // 方法
  function addTodo(todoItem) {
    // 如果传入了任务对象，直接添加
    if (todoItem && todoItem.text) {
      todos.value.push(todoItem);
      return;
    }
    
    // 兼容原有调用方式
    const text = newTodo.value.trim();
    if (text) {
      const id = Date.now();
      todos.value.push({ id, text, completed: false });
      newTodo.value = '';
    }
  }
  
  function removeTodo(index) {
    // 根据当前过滤器找到实际要删除的索引
    const todoToRemove = filteredTodos.value[index];
    const actualIndex = todos.value.findIndex(todo => todo.id === todoToRemove.id);
    if (actualIndex !== -1) {
      todos.value.splice(actualIndex, 1);
    }
  }
  
  function clearCompleted() {
    todos.value = todos.value.filter(todo => !todo.completed);
  }
  
  function updateLastSavedTime() {
    const now = new Date();
    lastSavedTime.value = now.toLocaleTimeString();
  }
  
  return {
    todos,
    newTodo,
    filter,
    lastSavedTime,
    filteredTodos,
    remainingCount,
    completedCount,
    completionRate,
    addTodo,
    removeTodo,
    clearCompleted,
    updateLastSavedTime
  };
}